/*
 * Copyright 2012 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package org.chacha.socket;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;

import org.chacha.entity.AuthRequest;
import org.chacha.entity.AuthResponse;
import org.chacha.entity.ResponseCode;
import org.chacha.util.JsonPojoMapper;
import org.junit.Test;

/**
 * 
 *	@author: hejing
 *	@date: 2012-11-26-下午02:01:35
 */
public class ClientSendThread implements Runnable {
	private String serverIP="127.0.0.1";
	private int port=9001;
	private String USERNAME="chacha499999";
	private String PASSWD="ddddddd";
	private CountDownLatch count;
	
	public ClientSendThread(CountDownLatch doneSignal) {
		this.count=doneSignal;
	}


	@Override
	@Test
	public void run() {

		try {
			AuthRequest auth=new AuthRequest();
			auth.setOpt(AuthRequest.CMD_AUTH);
			auth.put(AuthRequest.KEY_USERNAME,USERNAME);
			auth.put(AuthRequest.KEY_PASSWD, PASSWD);
			auth.put(AuthRequest.KEY_ACTION, AuthRequest.NEEDTOKEN);
			String jsonReq=JsonPojoMapper.toJson(auth,true);
			
			InetSocketAddress socketAddress = new InetSocketAddress(serverIP, port);
			SocketChannel channel = SocketChannel.open(socketAddress);
			Charset charset = Charset.forName("utf-8");
			channel.write(charset.encode(jsonReq));
			//System.out.println(Thread.currentThread().getName()+" "+jsonReq);
			ByteBuffer buffer = ByteBuffer.allocate(4096);
			AuthResponse response=null;
			if (channel.read(buffer) != -1) {
				buffer.flip();
				CharBuffer cb=charset.decode(buffer);
				buffer.clear();// 清空缓冲
				response=(AuthResponse)JsonPojoMapper.fromJson(cb.toString(), AuthResponse.class);
				System.out.println(Thread.currentThread().getName()+" "+cb.toString());
			}
			assertNotNull(response);
			assertTrue(response.getResult()==ResponseCode.SUCCESS);
			System.out.println(Thread.currentThread().getName()+" "+response.getToken());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			count.countDown();
		}
	}

}
